package tasklogic

import (
	"common/comOss"
	"common/comScript"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
	"os"
	"strings"
	"time"

	"task-rpc-server/internal/svc"
	"task-rpc-server/pb"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.TaskTableResp) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.TaskName == "" {
		return nil, errors.New("taskName is null")
	}
	if in.TaskType == "" {
		return nil, errors.New("taskType is null")
	}
	if in.Script == "" {
		return nil, errors.New("script is null")
	}
	db := l.svcCtx.DB.Table(model.TableNameTaskTable)
	err := db.Transaction(func(tx *gorm.DB) error {
		var (
			data = model.TaskTable{}
		)

		err := copier.CopyWithOption(&data, in, copier.Option{IgnoreEmpty: true})

		if err != nil {
			return err
		}
		//url, err := CreateOssFile(l.svcCtx.Config.OSS, data)
		//if err != nil {
		//	return err
		//}
		//data.URL = url
		t := time.Now()
		data.CreateTime = &t
		data.DeleTime = nil
		if err := tx.Create(&data).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}

var today = "script"

func CreateOssFile(OssConfig comOss.OSS, data model.TaskTable) (string, error) {
	if data.Script == "" {
		return "", nil
	}
	var str = ""
	name := data.TaskName + string(data.ID) + ".js"
	file, err := os.Create(name)
	defer func(file *os.File) {
		err := file.Close()
		logx.Infof("执行关闭文件流")
		if err != nil {
			return
		}
	}(file)
	if err != nil {
		return "", err
	}
	script := comScript.GetString(data.Script)
	_, err = file.WriteString(script)

	if err != nil {
		return str, err
	}
	response, err := comOss.GetOssResponse(OssConfig)
	if err != nil {
		return "", err
	}
	client, err := oss.New(OssConfig.Pint, response.Credentials.AccessKeyId, response.Credentials.AccessKeySecret, oss.SecurityToken(response.Credentials.SecurityToken))
	if err != nil {
		return "", err
	}
	// 获取存储空间
	bucket, err := client.Bucket(OssConfig.Bucket)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	objectKey := today + "/" + name
	// 检查文件夹是否存在，不存在则创建
	isExist, err := bucket.IsObjectExist(today + "/")
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	if !isExist {
		err := bucket.PutObject(today+"/", strings.NewReader(""))
		if err != nil {
			fmt.Println("Error:", err)
			return "", err
		}
	}
	err = bucket.PutObjectFromFile(objectKey, name)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	str, err = bucket.SignURL(objectKey, oss.HTTPGet, 60*60*24*3)
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}
	utils.DellFile(name)
	return str, nil
}
func DeleteOssFile(OssConfig comOss.OSS, data model.TaskTable) (bool, error) {
	if data.URL == "" {
		return true, nil
	}
	var flag = false
	fileName := today + "/" + data.TaskName + string(data.ID) + ".js"
	response, err := comOss.GetOssResponse(OssConfig)
	if err != nil {
		return false, err
	}
	client, err := oss.New(OssConfig.Pint, response.Credentials.AccessKeyId, response.Credentials.AccessKeySecret, oss.SecurityToken(response.Credentials.SecurityToken))
	if err != nil {
		return false, err
	}
	// 获取存储空间
	bucket, err := client.Bucket(OssConfig.Bucket)
	if err != nil {
		return false, err
	}
	err = bucket.DeleteObject(fileName)
	if err != nil {
		return false, err
	}
	flag = true
	return flag, nil
}
